package com.yiqi.lottery.feature.lottery.view;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.*;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.suozhang.framework.component.recyclerview.DividerItemDecoration;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.NetUtil;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.yiqi.lottery.R;
import com.yiqi.lottery.common.util.DateTool;
import com.yiqi.lottery.entity.bo.*;
import com.yiqi.lottery.entity.enums.DaletouType;
import com.yiqi.lottery.entity.enums.LotteryType;
import com.yiqi.lottery.feature.find.view.adapter.LuckyHistoryAdapter;
import com.yiqi.lottery.feature.lottery.contract.LottoContract;
import com.yiqi.lottery.feature.lottery.data.ConfirmLotteryOpe;
import com.yiqi.lottery.feature.lottery.data.LotteryData;
import com.yiqi.lottery.feature.lottery.dependencies.lotto.DaggerLottoComponent;
import com.yiqi.lottery.feature.lottery.dependencies.lotto.LottoPresenterModule;
import com.yiqi.lottery.feature.lottery.view.adapter.LuckyQianAdapter;
import com.yiqi.lottery.framework.DataServer;

import javax.inject.Inject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import static com.yiqi.lottery.feature.lottery.data.LotteryData.combination1;

public class LuckyNumberActivity extends BaseActivity implements SensorEventListener, LottoContract.View, LuckyQianAdapter.GetCheckedValue, BaseQuickAdapter.OnItemClickListener {

    @Inject
    LottoContract.Presenter mPresenter;
    @BindView(R.id.btn_gendan)
    TextView mTvFilter;
    @BindView(R.id.tv_lottery_current_qi)
    TextView mTvCurrentQi;
    @BindView(R.id.tv_lottery_current_date)
    TextView mTvCurrentDate;
    @BindView(R.id.img_xiala)
    ImageView mImgXiala;
    PopupWindow mPopupWindow;
    @BindView(R.id.view_toobar)
    RelativeLayout mViewToobar;
    @BindView(R.id.btn_lottery_list_more)
    ImageView mBtnLotteryListMore;
    @BindView(R.id.rv_lottery_lucky_list)
    RecyclerView mRvLotteryLuckyList;
    @BindView(R.id.rv_lottery_lucky_normal_qianqu)
    RecyclerView mRvLotteryLuckyNormalQianqu;
    @BindView(R.id.iv_show_shake)
    ImageView mIvShowShake;
    private static final int START_SHAKE = 0x1;
    private static final int AGAIN_SHAKE = 0x2;
    private static final int END_SHAKE = 0x3;
    @BindView(R.id.tv_show_first_qi)
    TextView mTvShowFirstQi;
    @BindView(R.id.tv_show_first_number)
    TextView mTvShowFirstNumber;
    @BindView(R.id.tv_lotte_show_zhu)
    TextView mTvLotteShowZhu;

    private boolean isShowList = false;
    private boolean isNormalChecked = true;

    private LuckyQianAdapter mLuckyAdapter;
    private SensorManager mSensorManager;
    private Sensor mAccelerometerSensor;
    private Vibrator mVibrator;//手机震动
    private SoundPool mSoundPool;//摇一摇音效
    private List<SelectItem> mSelectItems = new ArrayList<>();

    //记录摇动状态
    private boolean isShake = false;
    private MyHandler mHandler;
    private int mWeiChatAudio;

    private int mZhushu = 0;

    private LuckyHistoryAdapter mHistoryAdapter;
    HashMap<Integer, Vector<String>> mVectorHashMap;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_lucky_number;
    }

    @Override
    protected void initInjector() {
        DaggerLottoComponent.builder().lottoPresenterModule(new LottoPresenterModule(this)).build().inject(this);
    }

    private void setListShow(boolean isShow) {
        if (isShow) {
            isShowList = false;
            mRvLotteryLuckyList.setVisibility(View.GONE);
            mBtnLotteryListMore.setImageResource(R.drawable.icon_xiala_lucky);
        } else {
            isShowList = true;
            mRvLotteryLuckyList.setVisibility(View.VISIBLE);
            mBtnLotteryListMore.setImageResource(R.drawable.icon_xiala_lucky_down);
        }
    }


    @Override
    protected void initView() {
        mHandler = new MyHandler(this);

        //初始化SoundPool
        mSoundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
        mWeiChatAudio = mSoundPool.load(this, R.raw.weichat_audio, 1);

        //获取Vibrator震动服务
        mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    }

    @Override
    protected void initData() {
        mPresenter.getLotteryHistory(LotteryType.大乐透.getName());
        mPresenter.getCurrentQi();
        initHistoryData();
        initQianData();

        mLuckyAdapter.setNewData(DataServer.getNormalData());

    }

    @OnClick({R.id.btn_back, R.id.btn_filter, R.id.btn_yiwen, R.id.btn_lottery_list_more,
            R.id.btn_lottery_lucky_clear, R.id.btn_lottery_color_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_filter:
                changeImage(true);
                initmPopupWindowView(isNormalChecked);
                break;
            case R.id.btn_yiwen:
                break;
            case R.id.btn_lottery_list_more:
                setListShow(isShowList);
                break;
            case R.id.btn_lottery_lucky_clear:
                mZhushu = 0;
                mTvLotteShowZhu.setText(mZhushu + "注" + mZhushu * 2 + "元");
                if (mLuckyAdapter != null)
                    if (isNormalChecked) {
                        mLuckyAdapter.setNewData(DataServer.getNormalData());
                    } else {
                        mLuckyAdapter.setNewData(DataServer.getDanshiData());
                    }
                mLuckyAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_lottery_color_buy:

                if (isNormalChecked) {
                      toConfirmLotto();
                } else {
                    if (isCanBuyDantuo(mVectorHashMap)) {
                        toConfirmLotto();
                        break;
                    }
                }


        }
    }

    public  void toConfirmLotto(){
        if (mZhushu < 1) {
            T.showShort("最少选择一注！");
            return;
        }
        if (mZhushu > 10000) {
            T.showShort("方案金额不能超过两万！");
            return;
        }
        List<LuckySection> luckySections = mLuckyAdapter.getData();
        for (int i = 0; i < luckySections.size(); i++) {
            SelectItem selectItem = luckySections.get(i).t;
            if (selectItem != null && selectItem.isCheck()) {
                mSelectItems.add(selectItem);
            }
        }
        getLottery(mSelectItems, mZhushu);
        startActivity(new Intent(this, ConfirmBettingActivity.class));
        mZhushu = 0;
        mTvLotteShowZhu.setText(mZhushu + "注" + mZhushu * 2 + "元");
    }

    public void getLottery(List<SelectItem> selectItems, int zhu) {
        if (selectItems != null) {
            ConfirmLotteryBo confirmLotteryBo = new ConfirmLotteryBo();
            confirmLotteryBo.setName(LotteryData.getLottery(selectItems, !isNormalChecked)[0]);
            confirmLotteryBo.setHouName(LotteryData.getLottery(selectItems, !isNormalChecked)[1]);
            confirmLotteryBo.setCount(zhu);
            confirmLotteryBo.setPrize(2);
            confirmLotteryBo.setIsdantuo(!isNormalChecked);
            confirmLotteryBo.setType(DaletouType.DANSHI.getIndex());
            ConfirmLotteryOpe.insertData(this, confirmLotteryBo);
        }

    }

    public void initmPopupWindowView(boolean isNormal) {

        View contentView = LayoutInflater.from(this).inflate(R.layout.popup_lottery_type, null, false);
        mPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.showAsDropDown(mViewToobar);
        // 设置背景半透明
        backgroundAlpha(0.7f);

        mPopupWindow.setOnDismissListener(new popupDismissListener());

        contentView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
            }
        });
        RadioGroup radioGroup = contentView.findViewById(R.id.rg_type);
        RadioButton radioNormal = contentView.findViewById(R.id.btn_lottery_lucky_normal);
        RadioButton radioDantuo = contentView.findViewById(R.id.btn_lottery_lucky_dantuo);

        if (isNormal) {
            radioNormal.setChecked(true);
            radioDantuo.setChecked(false);
        } else {
            radioNormal.setChecked(false);
            radioDantuo.setChecked(true);
        }
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.btn_lottery_lucky_normal) {
                    mTvFilter.setText("普通投注");
                    mIvShowShake.setVisibility(View.VISIBLE);
                    isNormalChecked = true;
                    if (mLuckyAdapter != null) {
                        mLuckyAdapter.setNewData(DataServer.getNormalData());
                    }
                    dismss();
                } else if (checkedId == R.id.btn_lottery_lucky_dantuo) {
                    mTvFilter.setText("胆拖投注");
                    mIvShowShake.setVisibility(View.GONE);
                    isNormalChecked = false;
                    if (mLuckyAdapter != null) {
                        mLuckyAdapter.setNewData(DataServer.getDanshiData());
                    }
                    dismss();
                }
            }
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = bgAlpha; // 0.0-1.0
        this.getWindow().setAttributes(lp);
    }

    private void changeImage(boolean b) {

        if (b) {
            mImgXiala.setImageResource(R.drawable.icon_shouqi);
        } else {
            mImgXiala.setImageResource(R.drawable.icon_xiala2);
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        int type = event.sensor.getType();

        if (type == Sensor.TYPE_ACCELEROMETER) {
            //获取三个方向值
            float[] values = event.values;
            float x = values[0];
            float y = values[1];
            float z = values[2];

            if ((Math.abs(x) > 17 || Math.abs(y) > 17 || Math
                    .abs(z) > 17) && !isShake) {
                isShake = true;

                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            //开始震动 发出提示音 展示动画效果
                            mHandler.obtainMessage(START_SHAKE).sendToTarget();
                            Thread.sleep(500);

                            //再来一次震动提示
                            mHandler.obtainMessage(AGAIN_SHAKE).sendToTarget();
                            Thread.sleep(500);
                            mHandler.obtainMessage(END_SHAKE).sendToTarget();


                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void showCurrentSuccess(LuckyHistoryBo luckyHistoryBo) {
        mTvCurrentQi.setText("第" + luckyHistoryBo.getIssue() + "期");
        mTvCurrentDate.setText(DateTool.dateMinus10(luckyHistoryBo.getStopDate()) + "截至投注");
    }

    @Override
    public void showCurrentError(String ex) {
        T.showShort(ex);
    }

    @Override
    public void showCreateOrderSuccess(String luckyHistoryBo) {

    }

    @Override
    public void showCreateOrderError(String ex) {

    }

    @Override
    public void showLotteryHistorySuccess(List<LotteryHistoryBo> resultBos) {
        if (resultBos != null) {
            LotteryHistoryBo lotteryHistoryBo = resultBos.get(0);
            mTvShowFirstQi.setText("第" + lotteryHistoryBo.getIssue() + "期");

            StringBuilder sb = new StringBuilder(lotteryHistoryBo.getCode());
            sb.replace(14, 15, "\t|\t");
            mTvShowFirstNumber.setText("开奖：" + sb.toString().replaceAll("-", "  "));

            resultBos = resultBos.subList(1, 10);
            mHistoryAdapter.setNewData(resultBos);

        }


    }

    @Override
    public void showLotteryHistoryError(String error) {

    }

    @Override
    public void getValue() {



        if (isNormalChecked) {
            getNormalResultData();
        } else {
            getDanshiResultData(mLuckyAdapter.getData());
        }

    }

    /**
     * 获取胆施投注的数据
     */
    void getDanshiResultData(List<LuckySection> luckySections) {

        mVectorHashMap = new HashMap<>();
        Vector<String> mQianDan = new Vector<>();
        Vector<String> mQianTuo = new Vector<>();
        Vector<String> mHouDan = new Vector<>();
        Vector<String> mHouTuo = new Vector<>();

        List<SelectItem> selectItemList = new ArrayList<>();
        for (int i = 0; i < luckySections.size(); i++) {
            SelectItem selectItem = luckySections.get(i).t;
            if (selectItem != null && selectItem.getName() != null) {
                selectItemList.add(selectItem);
            }
        }

        for (int i = 0; i < selectItemList.size(); i++) {
            SelectItem selectItem = selectItemList.get(i);
            if (selectItem.isCheck() && selectItem.getDantuoType() == 1) {
                mQianDan.add(selectItem.getName() + "");
            } else if (selectItem.isCheck() && selectItem.getDantuoType() == 2) {
                mQianTuo.add(selectItem.getName() + "");
            } else if (selectItem.isCheck() && selectItem.getDantuoType() == 3) {
                mHouDan.add(selectItem.getName() + "");
            } else if (selectItem.isCheck() && selectItem.getDantuoType() == 4) {
                mHouTuo.add(selectItem.getName() + "");
            }
        }
        Logger.e("\nmQianDan---->" + mQianDan + "\nmQianTuo---->" +mQianTuo +
                "\nmHouDan---->" + mHouDan + "\nmHouTuo---->" +mHouTuo+
                "\nC---->" + mZhushu);
        mVectorHashMap.put(0, mQianDan);
        mVectorHashMap.put(2, mQianTuo);
        mVectorHashMap.put(1, mHouDan);
        mVectorHashMap.put(3, mHouTuo);



        mZhushu = LotteryData.calculateDaleDanTuo(mVectorHashMap, 5, 2);
        mTvLotteShowZhu.setText(mZhushu + "注" + mZhushu * 2 + "元");
    }

    public boolean isCanBuyDantuo(HashMap<Integer, Vector<String>> vectorHashMap) {
        if (vectorHashMap == null||vectorHashMap.size()==0) {
            T.showShort("请先选择1注！");
            return false;
        }
        Vector<String> mQianDan = vectorHashMap.get(0);
        Vector<String> mQianTuo = vectorHashMap.get(2);
        Vector<String> mHouDan = vectorHashMap.get(1);
        Vector<String> mHouTuo = vectorHashMap.get(3);

        if (mQianDan == null || mQianDan.size() < 1) {
            T.showShort("前区最少选择1个胆码！");
            return false;
        }
        if (mQianDan.size() > 4) {
            T.showShort("前区最多选择4个胆码！");
            return false;
        }
        if (mQianTuo == null || mQianTuo.size() < 2) {
            T.showShort("前区最少选择2个拖码！");
            return false;
        }

        boolean isHong = mQianTuo.retainAll(mQianDan);
        boolean isHong2 = mQianDan.retainAll(mQianTuo);
        if (!isHong){
            T.showShort("红区不能有相同的号！");
            return  false;
        }if (!isHong2){
            T.showShort("红区不能有相同的号！");
            return  false;
        }

        if (mHouDan == null || mHouDan.size() != 1) {
            T.showShort("后区最多选择1个胆码！");
            return false;
        }
        if (mHouTuo == null || mHouTuo.size() < 2) {
            T.showShort("后区最少选择2个拖码！");
            return false;
        }


        boolean isLan = mHouDan.retainAll(mHouTuo);
        if (!isLan){
            T.showShort("蓝区不能有相同的号！");
            return  false;
        }
        return true;
    }

    /**
     * 获取普通投注的数据
     */
    void getNormalResultData() {
        int m = 0;
        int n = 0;

        List<SelectItem> selectItemList = new ArrayList<>();
        List<LuckySection> luckySections = mLuckyAdapter.getData();
        for (int i = 0; i < luckySections.size(); i++) {
            SelectItem selectItem = luckySections.get(i).t;
            if (selectItem != null && selectItem.getName() != null) {
                selectItemList.add(selectItem);

            }
        }


        for (int i = 0; i < selectItemList.size(); i++) {
            SelectItem selectItem = selectItemList.get(i);
            if (selectItem.isCheck() && selectItem.getType() == 1) {
                m++;
            } else if (selectItem.isCheck() && selectItem.getType() == 2) {
                n++;
            }
        }

        mZhushu = combination1(m, 5) * combination1(n, 2);
        mTvLotteShowZhu.setText(mZhushu + "注" + mZhushu * 2 + "元");
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    class popupDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
            changeImage(false);
        }
    }

    public void dismss() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
            mPopupWindow = null;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mZhushu = 0;
        mTvLotteShowZhu.setText(mZhushu + "注" + mZhushu * 2 + "元");
        if (mLuckyAdapter != null) {
            if (isNormalChecked) {
                mLuckyAdapter.setNewData(DataServer.getNormalData());
            } else {
                mLuckyAdapter.setNewData(DataServer.getDanshiData());
            }

        }
        mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
        if (mSensorManager != null) {
            //获取加速度传感器
            mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            if (mAccelerometerSensor != null) {
                mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_UI);
            }
        }
    }

    @Override
    protected void onPause() {

        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        dismss();
        if (mLuckyAdapter != null) {
            mLuckyAdapter.notifyDataSetChanged();

        }
        if (mSelectItems != null) {
            mSelectItems.clear();
        }
    }

    public void initHistoryData() {
        mRvLotteryLuckyList.setLayoutManager(new LinearLayoutManager(this));
        mRvLotteryLuckyList.addItemDecoration(new DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(2));
        mHistoryAdapter = new LuckyHistoryAdapter();
        mHistoryAdapter.bindToRecyclerView(mRvLotteryLuckyList);
    }

    public void initQianData() {
        mRvLotteryLuckyNormalQianqu.setLayoutManager(new GridLayoutManager(this, 7));
        mLuckyAdapter = new LuckyQianAdapter(null);
        mLuckyAdapter.bindToRecyclerView(mRvLotteryLuckyNormalQianqu);
        mLuckyAdapter.setOnItemChecked(this);
        mLuckyAdapter.setOnItemClickListener(this);
    }

    private class MyHandler extends Handler {
        private WeakReference<LuckyNumberActivity> mReference;
        private LuckyNumberActivity mActivity;

        public MyHandler(LuckyNumberActivity activity) {
            mReference = new WeakReference<LuckyNumberActivity>(activity);
            if (mReference != null) {
                mActivity = mReference.get();
            }
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case START_SHAKE:
//                    mActivity.mSoundPool.play(mActivity.mWeiChatAudio, 1, 1, 0, 0, 1);
                    break;
                case AGAIN_SHAKE:
                    if (isNormalChecked) {
                        mLuckyAdapter.setNewData(DataServer.getNormalRandomData());
                        mZhushu = 1;
                        mTvLotteShowZhu.setText(mZhushu + "注" + mZhushu * 2 + "元");
                        mActivity.mVibrator.vibrate(300);
                    }
                    break;
                case END_SHAKE:
                    //整体效果结束, 将震动设置为false
                    mActivity.isShake = false;
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ConfirmLotteryOpe.deleteAllData(this);
    }

}
